package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.Point;
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Configuracion extends javax.swing.JInternalFrame {
    private String fondo="";
    private JDesktopPane panel;
    private JFileChooser selector=new JFileChooser();
    private AbstractBorder borde_default;
    public Configuracion(JDesktopPane p,AbstractBorder borde) {
        initComponents();
        this.setLocation(new Point(70, 0));
        this.panel=p;
        this.borde_default=borde;
        selector.setFileFilter(new FileNameExtensionFilter("Imagenes",new String[]{"jpg","jpeg","png","gif"}));
        selector.setMultiSelectionEnabled(false);
        jbtnFondo.setVisible(false);
        ConfiguracionUsuario conf=Conexion.ObtenerConfiguracion();
        if(conf!=null){
            jchkVencimiento.setSelected(conf.AvisaVencidos());
            ((SpinnerNumberModel)jspMeses.getModel()).setValue(conf.getMeses());
            jchkBitacora.setSelected(conf.UsaBitacora());
            jrbPorDefecto.setSelected(conf.getFondoPantalla().equals(""));
            GestionarBotonesFondo(jrbPorDefecto.isSelected());
            fondo=conf.getFondoPantalla();
        }
        if(Conexion.tipo==Util.Tipo.USUARIO){
            jpBitacora.setVisible(false);
            jpRespaldo.setVisible(false);
        }
        this.pack();
        jbtnGuardar.setLocation((this.getWidth()-jbtnGuardar.getWidth())/2,jbtnGuardar.getY());
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpVencimiento = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jspMeses = new javax.swing.JSpinner();
        jchkVencimiento = new javax.swing.JCheckBox();
        jpFondo = new javax.swing.JPanel();
        jbtnFondo = new javax.swing.JButton();
        jrbPorDefecto = new javax.swing.JRadioButton();
        jrbPersonalizado = new javax.swing.JRadioButton();
        jpBitacora = new javax.swing.JPanel();
        jchkBitacora = new javax.swing.JCheckBox();
        jpRespaldo = new javax.swing.JPanel();
        jbtnRespaldo = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Configuración");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/cofiguracion.png"))); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jpVencimiento.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Periodo de Aviso de Vencimiento", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jLabel1.setText("Meses:");

        jspMeses.setModel(new javax.swing.SpinnerNumberModel(6, 1, 12, 1));
        jspMeses.setToolTipText("Meses");

        jchkVencimiento.setSelected(true);
        jchkVencimiento.setText("Activado");
        jchkVencimiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jchkVencimientoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpVencimientoLayout = new javax.swing.GroupLayout(jpVencimiento);
        jpVencimiento.setLayout(jpVencimientoLayout);
        jpVencimientoLayout.setHorizontalGroup(
            jpVencimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpVencimientoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jchkVencimiento)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jspMeses, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jpVencimientoLayout.setVerticalGroup(
            jpVencimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpVencimientoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpVencimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jspMeses, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jchkVencimiento))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        jpFondo.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Fondo de Pantalla del Sistema", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jbtnFondo.setText("Seleccionar Fondo");
        jbtnFondo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnFondoActionPerformed(evt);
            }
        });

        jrbPorDefecto.setSelected(true);
        jrbPorDefecto.setText("Por Defecto");
        jrbPorDefecto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbPorDefectoActionPerformed(evt);
            }
        });

        jrbPersonalizado.setText("Personalizado");
        jrbPersonalizado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbPersonalizadoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpFondoLayout = new javax.swing.GroupLayout(jpFondo);
        jpFondo.setLayout(jpFondoLayout);
        jpFondoLayout.setHorizontalGroup(
            jpFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpFondoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jrbPorDefecto)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 66, Short.MAX_VALUE)
                .addComponent(jrbPersonalizado)
                .addContainerGap())
            .addGroup(jpFondoLayout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addComponent(jbtnFondo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpFondoLayout.setVerticalGroup(
            jpFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpFondoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jrbPorDefecto)
                    .addComponent(jrbPersonalizado))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnFondo))
        );

        jpBitacora.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Activar/Desactivar Bitácora", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jchkBitacora.setSelected(true);
        jchkBitacora.setText("Activado");
        jchkBitacora.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jchkBitacoraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpBitacoraLayout = new javax.swing.GroupLayout(jpBitacora);
        jpBitacora.setLayout(jpBitacoraLayout);
        jpBitacoraLayout.setHorizontalGroup(
            jpBitacoraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpBitacoraLayout.createSequentialGroup()
                .addGap(80, 80, 80)
                .addComponent(jchkBitacora)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpBitacoraLayout.setVerticalGroup(
            jpBitacoraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpBitacoraLayout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addComponent(jchkBitacora)
                .addContainerGap())
        );

        jpRespaldo.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Respaldo de Base de Datos", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jbtnRespaldo.setText("Realizar Respaldo");

        javax.swing.GroupLayout jpRespaldoLayout = new javax.swing.GroupLayout(jpRespaldo);
        jpRespaldo.setLayout(jpRespaldoLayout);
        jpRespaldoLayout.setHorizontalGroup(
            jpRespaldoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpRespaldoLayout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addComponent(jbtnRespaldo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpRespaldoLayout.setVerticalGroup(
            jpRespaldoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpRespaldoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbtnRespaldo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jpFondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jpBitacora, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jpVencimiento, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jpRespaldo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(106, 106, 106)
                        .addComponent(jbtnGuardar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpBitacora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpRespaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnGuardar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jchkVencimientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jchkVencimientoActionPerformed
        jchkVencimiento.setText(jchkVencimiento.isSelected()?"Activado":"Desactivado");
    }//GEN-LAST:event_jchkVencimientoActionPerformed
    private void jchkBitacoraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jchkBitacoraActionPerformed
        jchkBitacora.setText(jchkBitacora.isSelected()?"Activado":"Desactivado");
    }//GEN-LAST:event_jchkBitacoraActionPerformed
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        try {
            File archivo=new File("configuracion.jagg");
            if(!archivo.exists())
                archivo.createNewFile();
            ArrayList<ConfiguracionUsuario> configuraciones=Conexion.ObtenerConfiguraciones(archivo);
            ObjectOutputStream escritor=new ObjectOutputStream(new FileOutputStream(archivo,false));
            ConfiguracionUsuario usuario=new ConfiguracionUsuario(Conexion.ID,(jpFondo.isVisible()?(jrbPorDefecto.isSelected()?"":fondo):""),
                    (jpVencimiento.isVisible()?jchkVencimiento.isSelected():true),(jpBitacora.isVisible()?jchkBitacora.isSelected():true),
                    (jpVencimiento.isVisible()?Integer.parseInt(jspMeses.getValue().toString()):6));
            configuraciones=ConfiguracionDeUsuario(configuraciones,usuario);
            escritor.writeObject(configuraciones);
        } catch (Exception ex) {System.err.println(ex.getMessage());}
        if(jrbPorDefecto.isSelected())
            panel.setBorder(borde_default);
        if(jpBitacora.isVisible())
            Conexion.EjecutarConsulta("UPDATE usuario SET guardar_bitacora='"+(jchkBitacora.isSelected()?"s":"n")+"'");
        JOptionPane.showMessageDialog(null,"Configuración Guardada","Configuración",JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private ArrayList<ConfiguracionUsuario> ConfiguracionDeUsuario(ArrayList<ConfiguracionUsuario> lista,ConfiguracionUsuario nuevo){
        for(ConfiguracionUsuario c:lista){
            if(c.getIdUsuario().equals(nuevo.getIdUsuario())){
                c.setFondoPantalla(nuevo.getFondoPantalla());
                c.setAvisarVencidos(nuevo.AvisaVencidos());
                c.setUsarBitacora(nuevo.UsaBitacora());
                c.setMeses(nuevo.getMeses());
                return lista;
            }
        }
        lista.add(nuevo);
        return lista;
    }
    private void jrbPorDefectoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbPorDefectoActionPerformed
        GestionarBotonesFondo(jrbPorDefecto.isSelected());
    }//GEN-LAST:event_jrbPorDefectoActionPerformed
    private void jrbPersonalizadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbPersonalizadoActionPerformed
        GestionarBotonesFondo(!jrbPersonalizado.isSelected());
    }//GEN-LAST:event_jrbPersonalizadoActionPerformed
    private void GestionarBotonesFondo(boolean valor){
        jrbPorDefecto.setSelected(valor);
        jrbPersonalizado.setSelected(!valor);
        jbtnFondo.setVisible(!valor);
    }
    private void jbtnFondoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnFondoActionPerformed
        if(selector.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
            fondo=selector.getSelectedFile().getAbsolutePath();
            ImagenFondo img=new ImagenFondo(fondo);
            img.setDimensionesPanel(panel.getWidth(),panel.getHeight());
            panel.setBorder(img);
        }
    }//GEN-LAST:event_jbtnFondoActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jbtnFondo;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JButton jbtnRespaldo;
    private javax.swing.JCheckBox jchkBitacora;
    private javax.swing.JCheckBox jchkVencimiento;
    private javax.swing.JPanel jpBitacora;
    private javax.swing.JPanel jpFondo;
    private javax.swing.JPanel jpRespaldo;
    private javax.swing.JPanel jpVencimiento;
    private javax.swing.JRadioButton jrbPersonalizado;
    private javax.swing.JRadioButton jrbPorDefecto;
    private javax.swing.JSpinner jspMeses;
    // End of variables declaration//GEN-END:variables
}